package com.own.business.resource.core.model;

import com.own.business.resource.core.model.base.BaseUploadModel;
import com.own.component.common.exception.BusinessSimpleException;
import com.own.component.common.util.FileMd5Util;
import com.own.exception.ExceptionEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * UploadModel
 *
 * @author chenxueli
 * @date 2023-07-07 16:44:41
 */
@Slf4j
public class UploadMultipartModel extends BaseUploadModel {

    /**
     * 文件流信息
     */
    private final MultipartFile multipartFile;

    /**
     * 文件上传
     *
     * @param multipartFile 文件信息
     */
    public UploadMultipartModel(MultipartFile multipartFile) {
        this(multipartFile, true);
    }

    /**
     * 文件上传
     *
     * @param multipartFile 文件信息
     * @param calcMd5       是否计算md5
     */
    public UploadMultipartModel(MultipartFile multipartFile, boolean calcMd5) {
        if (multipartFile == null) {
            throw new BusinessSimpleException(ExceptionEnum.Resource.FILE_NOT_EXIST);
        }
        this.multipartFile = multipartFile;
        // 获取后缀信息
        this.setOldFileName(multipartFile.getOriginalFilename());
        this.setFileSize(multipartFile.getSize());
        if (calcMd5) {
            this.setMd5(FileMd5Util.get(multipartFile));
        }
        this.init();
    }

    /**
     * 设置文件流信息
     *
     * @return 文件流信息
     */
    @Override
    public InputStream setInputStream() {
        try {
            return multipartFile.getInputStream();
        } catch (IOException e) {
            throw new BusinessSimpleException(ExceptionEnum.Resource.INPUT_STREAM_WRROR);
        }
    }

}
